package znbkSameQuesTranslate.SQ_TLXZ;

import android.animation.Animator;
import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.animation.ValueAnimator;
import android.annotation.SuppressLint;
import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.os.Message;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Html;
import android.text.SpannableString;
import android.text.method.LinkMovementMethod;
import android.text.method.ScrollingMovementMethod;
import android.util.Log;
import android.view.View;
import android.view.animation.Animation;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.TextView;

import com.example.znbk.znbklibrary.base.AnswerViewPagerAdapter;
import com.example.znbk.znbklibrary.base.BaseFragment;
import com.example.znbk.znbklibrary.util.LancooUtils;
import com.example.znbk.znbklibrary.voicePlayer.VoicePlayer;
import com.lancoo.znbkxx.R;
import com.tt.CoreType;
import com.tt.QType;
import com.tt.SkEgnManager;
import com.tt.listener.OnRecordListener;
import com.tt.widget.AudioRecoderUtils;
import com.tt.widget.JSONTool;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import znbkBkfx.AboutCountDowm.CountDownView;
import znbkBkfx.AboutKnowledgePoint.HighLightKeyWordUtil;
import znbkSameQuesTranslate.GetSameQuesJson.SameQuesPaperEntity;
import znbkSameQuesTranslate.SameQuesActivity;

@SuppressLint("ValidFragment")
public class SQxlTlxzFragment extends BaseFragment {

    private String AudioPath = "";
    private void getEntityInfor(){
        AudioPath = sameQuesPaperEntity.get(quesIndex).getQuesFromTK().getAudioList().get(0).getPath();
    }

    private List<SameQuesPaperEntity> sameQuesPaperEntity;
    private int quesIndex = -1;
    private CallBackFragmentTlxz callBackFragmentTlxz;
    public SQxlTlxzFragment(List<SameQuesPaperEntity>  sameQuesPaperEntity, final int quesIndex,CallBackFragmentTlxz callBackFragmentTlxz){
        this.sameQuesPaperEntity = sameQuesPaperEntity;
        this.quesIndex = quesIndex;
        this.callBackFragmentTlxz = callBackFragmentTlxz;
        getEntityInfor();
    }

    @Override
    protected int createLayout() {
        return R.layout.sq_fragment_tlxz;
    }

    private ImageButton mIBtnPlayPause;//音频控制按钮
    private SeekBar mSbMusicProgress;//音频进度条
    private TextView mTvMusicTime;//播放时间点
    private TextView mTvListenScript;

    private ViewPager mVpAnswer;
    private ArrayList<View> list;
    public AnswerViewPagerAdapter mAnswerViewPagerAdapter;

    private RelativeLayout mRlMyBrowseBg;
    private CountDownView mCdvMyBrowse;
    private RelativeLayout mRlMyRecordBg;
    private ImageView mIvMyRecordMi;
    private Drawable drawableMi;
    private TextView mTvHintAnswerType;
    public  boolean isVoicePlayingEnd = false;

    @Override
    protected void initView(View view) {
        //显示播放器
        mIBtnPlayPause = view.findViewById(R.id.ibtn_audioIcon);
        mSbMusicProgress = view.findViewById(R.id.sb_musicProgress);
        mTvMusicTime = view.findViewById(R.id.tv_musicTime);
        mTvListenScript = view.findViewById(R.id.tv_listenScript);
        mTvListenScript.setMovementMethod(ScrollingMovementMethod.getInstance());

        /*
        * 初始化加载听力原文
        * */
        String ListenScript  = sameQuesPaperEntity.get(quesIndex).getQuesFromTK().getAudioList().get(0).getText();
        CharSequence ListenScriptA = Html.fromHtml("听力原文<br><br>"+ListenScript);
        int ImprotantZSDSize = sameQuesPaperEntity.get(quesIndex).getQuesFromTK().getImprotantZSD().size();
        String[] keyword = new String[ImprotantZSDSize];
        String[] keywordCode = new String[ImprotantZSDSize];
        for(int i=0;i<ImprotantZSDSize;i++){
            keyword[i] = sameQuesPaperEntity.get(quesIndex).getQuesFromTK().getImprotantZSD().get(i).getName();
            keywordCode[i] = sameQuesPaperEntity.get(quesIndex).getQuesFromTK().getImprotantZSD().get(i).getCode();
        }
        SpannableString highlightText = HighLightKeyWordUtil.highlight(ListenScriptA.toString(), keyword, keywordCode,"#FF0000");
        mTvListenScript.setText(highlightText);
        mTvListenScript.setMovementMethod(LinkMovementMethod.getInstance());//设置可点击状态

        int SubmitState = sameQuesPaperEntity.get(quesIndex).getFavouriteAndNote().getSubmitState();
        if(SubmitState==2){
            mTvListenScript.setVisibility(View.VISIBLE);
        }else{
            mTvListenScript.setVisibility(View.GONE);
        }

        mVoicePlayer = new VoicePlayer(mSbMusicProgress, AudioPath, mTvMusicTime, mIBtnPlayPause,
                false, true, false, new VoicePlayer.FinishPlay() {
            @Override
            public void onFinishPlay() {
                isVoicePlayingEnd = true;

                final Handler mH = new Handler();
                mH.post(new Runnable() {
                    @Override
                    public void run() {
                        int SubmitState = sameQuesPaperEntity.get(quesIndex).getFavouriteAndNote().getSubmitState();
                        if (SubmitState != 2) {
                            showRecordMiView();//开启录音功能动画
                            mRecoderUtils = new AudioRecoderUtils();
                            SkEgnManager.getInstance(getActivity()).startRecord(mCoreType, "", QType.QTYPE_EMPTY, mOnRecordListener);
                            mRecoderUtils.startRecord();
                        }
                        mH.removeCallbacks(this);
                    }
                });
            }
        });

        //显示TlxzAnswer内容
        //显示Answer信息
        mVpAnswer = view.findViewById(R.id.vp_answerTlxz);
        list = new ArrayList<>();
        list.clear();
        int totalItemCount =sameQuesPaperEntity.get(quesIndex).getQuesFromTK().getTotalItemCount();
        for (int i = 0; i < totalItemCount; i++) {
                RecyclerView mRvAnswer = new RecyclerView(getActivity());
                mRvAnswer.setLayoutManager(new LinearLayoutManager(getActivity()));//必须先设置LayoutManager
                SQxlTlxzAnswerAdapter mAnswerAdapter = new SQxlTlxzAnswerAdapter(getActivity(),
                        sameQuesPaperEntity,quesIndex,i,new SQxlTlxzAnswerAdapter.CallBackAdapterTlxz() {
                    @Override
                    public void callAnsweredAll() {

                        SameQuesActivity.mVpSameQues.setScrollble(false);//禁止界面滑动事件
                        pause();//关闭音频播放
                        if(mRlMyRecordBg.getVisibility()==View.VISIBLE) {
                            hideRecordMiView();
                        }else {
                            //显示听力原文
                            mTvListenScript.setVisibility(View.VISIBLE);
                            refreshAnswerAdapter();
                            //执行提交操作
                            final Handler mH = new Handler();
                            mH.postDelayed(new Runnable() {
                                @Override
                                public void run() {
                                    callBackFragmentTlxz.submitKgtQuesAnswer();
                                    SameQuesActivity.mVpSameQues.setScrollble(true);
                                    mH.removeCallbacks(this);
                                }
                            },1000);
                        }

                    }

                });
                mRvAnswer.setAdapter(mAnswerAdapter);
                list.add(mRvAnswer);
        }
        mAnswerViewPagerAdapter = new AnswerViewPagerAdapter(list);
        mVpAnswer.setAdapter(mAnswerViewPagerAdapter);
        sameQuesPaperEntity.get(quesIndex).getFavouriteAndNote().setCurrentSubChildAnswerIndex(0);
        mVpAnswer.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int i, float v, int i1) {

            }

            @Override
            public void onPageSelected(int i) {
                sameQuesPaperEntity.get(quesIndex).getFavouriteAndNote().setCurrentSubChildAnswerIndex(i);
            }

            @Override
            public void onPageScrollStateChanged(int i) {

            }
        });

        //显示浏览倒计时
        mRlMyBrowseBg = view.findViewById(R.id.rl_myBrowseBg);
        mCdvMyBrowse =  view.findViewById(R.id.cdv_myBrowse);
        mCdvMyBrowse.setCountdownTime(5);
        mCdvMyBrowse.setRingWidth(12);
        mCdvMyBrowse.setAddCountDownListener(new CountDownView.OnCountDownFinishListener() {
            @Override
            public void countDownFinished() {
                LancooUtils.showShort(getActivity(),"倒计时结束");
                hideBrowseView();
                play();
                sameQuesPaperEntity.get(quesIndex).getFavouriteAndNote().setSubmitState(1);
            }
        });
        mCdvMyBrowse.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                mCdvMyBrowse.pauseCountDown();

                sameQuesPaperEntity.get(quesIndex).getFavouriteAndNote().setSubmitState(1);
                hideBrowseView();//开启隐藏浏览view动画
                play();
            }
        });



        //显示话咪
        mRlMyRecordBg = view.findViewById(R.id.rl_myRecordBg);
        mRlMyRecordBg.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                return;
            }
        });
        mIvMyRecordMi = view.findViewById(R.id.iv_myRecordMi);
        drawableMi = mIvMyRecordMi.getDrawable();

        mTvHintAnswerType = view.findViewById(R.id.tv_hintAnswerType);
        ObjectAnimator objectAnimator = ObjectAnimator.ofInt(mTvHintAnswerType,"textColor",0xffffffff,0xffff00aa);
        objectAnimator.setDuration(2000);
        objectAnimator.setRepeatCount(Animation.INFINITE);
        objectAnimator.setRepeatMode(ValueAnimator.REVERSE);
        objectAnimator.start();

    }

    @SuppressLint("NewApi")
    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        int SubmitState = sameQuesPaperEntity.get(quesIndex).getFavouriteAndNote().getSubmitState();

        if(isVisibleToUser){
            Log.e("setUserVisibleHint","================AnswerState===================="+SubmitState);
            if(SubmitState==0) {
                final Handler mH = new Handler();
                mH.post(new Runnable() {
                    @Override
                    public void run() {

                        if(mCdvMyBrowse!=null) {
                            if (mCdvMyBrowse.isCountDownRunning()) {
                                mCdvMyBrowse.resumeCountDown();
                            } else {
                                showBrowseView();
                                mCdvMyBrowse.startCountDown();
                            }
                            mH.removeCallbacks(this);
                        }else{
                            mH.post(this);
                        }

                    }
                });
            }else if(SubmitState==1){
                if(!isVoicePlayingEnd) {
                    play();
                }
            }else if(SubmitState==2){
                pause();
            }

        }else{
            pause();
            if(mCdvMyBrowse!=null) {
                mCdvMyBrowse.pauseCountDown();
            }
        }
    }

    private void showBrowseView(){
        if(mRlMyBrowseBg.getVisibility()==View.GONE) {
            ObjectAnimator translationY = ObjectAnimator.ofFloat(mRlMyBrowseBg, View.TRANSLATION_Y, 300f, 0f);
            AnimatorSet setShow = new AnimatorSet();
            setShow.playTogether(translationY);
            setShow.setDuration(300);
            setShow.addListener(new Animator.AnimatorListener() {
                @Override
                public void onAnimationStart(Animator animation) {
                    mRlMyBrowseBg.setVisibility(View.VISIBLE);
                }

                @Override
                public void onAnimationEnd(Animator animation) {

                }

                @Override
                public void onAnimationCancel(Animator animation) {

                }

                @Override
                public void onAnimationRepeat(Animator animation) {

                }
            });
            setShow.start();
        }
    }
    private void hideBrowseView(){
        if(mRlMyBrowseBg.getVisibility()==View.VISIBLE) {
            ObjectAnimator translationY = ObjectAnimator.ofFloat(mRlMyBrowseBg, View.TRANSLATION_Y, 0f, 300f);
            AnimatorSet setShow = new AnimatorSet();
            setShow.playTogether(translationY);
            setShow.setDuration(300);
            setShow.addListener(new Animator.AnimatorListener() {
                @Override
                public void onAnimationStart(Animator animation) {

                }

                @Override
                public void onAnimationEnd(Animator animation) {
                    mRlMyBrowseBg.setVisibility(View.GONE);
                }

                @Override
                public void onAnimationCancel(Animator animation) {

                }

                @Override
                public void onAnimationRepeat(Animator animation) {

                }
            });
            setShow.start();
        }
    }

    private void showRecordMiView(){
        if(mRlMyRecordBg.getVisibility()==View.GONE) {
            ObjectAnimator translationY = ObjectAnimator.ofFloat(mRlMyRecordBg, View.TRANSLATION_Y, 300f, 0f);
            AnimatorSet setShow = new AnimatorSet();
            setShow.playTogether(translationY);
            setShow.setDuration(300);
            setShow.addListener(new Animator.AnimatorListener() {
                @Override
                public void onAnimationStart(Animator animation) {
                    mRlMyRecordBg.setVisibility(View.VISIBLE);
                }

                @Override
                public void onAnimationEnd(Animator animation) {

                }

                @Override
                public void onAnimationCancel(Animator animation) {

                }

                @Override
                public void onAnimationRepeat(Animator animation) {

                }
            });
            setShow.start();
        }
    }
    private void hideRecordMiView(){
        if(mRlMyRecordBg.getVisibility()==View.VISIBLE) {
            SameQuesActivity.mVpSameQues.setScrollble(false);
            ObjectAnimator translationY = ObjectAnimator.ofFloat(mRlMyRecordBg, View.TRANSLATION_Y, 0f, 300f);
            AnimatorSet setShow = new AnimatorSet();
            setShow.playTogether(translationY);
            setShow.setDuration(300);
            setShow.addListener(new Animator.AnimatorListener() {
                @Override
                public void onAnimationStart(Animator animation) {

                }

                @Override
                public void onAnimationEnd(Animator animation) {
                    mRlMyRecordBg.setVisibility(View.GONE);
                    //显示听力原文
                    mTvListenScript.setVisibility(View.VISIBLE);
                    //刷新作答区域
                    refreshAnswerAdapter();
                    //执行提交操作
                    final Handler mH = new Handler();
                    mH.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            callBackFragmentTlxz.submitKgtQuesAnswer();
                            SameQuesActivity.mVpSameQues.setScrollble(true);
                            mH.removeCallbacks(this);
                        }
                    },1000);

                }

                @Override
                public void onAnimationCancel(Animator animation) {

                }

                @Override
                public void onAnimationRepeat(Animator animation) {

                }
            });
            setShow.start();
        }
    }


    private AudioRecoderUtils mRecoderUtils;
    private String  mCoreType = CoreType.EN_ASR_REC;
    /*
     * 话咪录音操作
     * */
    OnRecordListener mOnRecordListener = new OnRecordListener() {
        @Override
        public void onRecordStart() {
            //开始录制
            Log.e("==onRecordingAA==","========vad_status==========="+"121212121212");
        }
        @Override
        public void onRecording(int vad_status, int sound_intensity) {
            //录制中
            int SubmitState = sameQuesPaperEntity.get(quesIndex).getFavouriteAndNote().getSubmitState();
            if(SubmitState==2){
                SkEgnManager.getInstance(getActivity()).stopRecord();
                mRecoderUtils.stopRecord();
            }
            Log.e("==onRecordingAA==","========vad_status==========="+vad_status);
            Log.e("==onRecordingBB==","=========sound_intensity==========="+sound_intensity);
            showRecordVolumeSize(sound_intensity);
            if(vad_status==2){
                SkEgnManager.getInstance(getActivity()).stopRecord();
                mRecoderUtils.stopRecord();
            }
        }
        @Override
        public void onRecordEnd(String result) {
            //录制结束
            try {
                final JSONObject json = new JSONObject(result);
                Log.e("17kouyuAAA", "返回json===>" + result);
                String choiceResult = "";
                if(!getResult(result).equals("")) {
                    choiceResult = getResult(result);
                }
                Log.e("==AFGAFG==","========KKKKK》》==========="+choiceResult);
                int SubChildAnsweringIndex = sameQuesPaperEntity.get(quesIndex).getFavouriteAndNote().getCurrentSubChildAnswerIndex();//获取当前作答小题的小题编号
                int OptionSize = sameQuesPaperEntity.get(quesIndex).getQuesFromTK().getChildList().//获取小题对应的选项个数
                        get(SubChildAnsweringIndex).getSubChildList().get(0).getOptionList().size();



                if(choiceResult.equals("a")||choiceResult.equals("hey")||
                        choiceResult.equals("b")||  choiceResult.equals("boy")||
                        choiceResult.equals("c")||
                        choiceResult.equals("d")||choiceResult.equals("dog")){

                    if(choiceResult.equals("a")||choiceResult.equals("hey")){
                        if(OptionSize>=1) {
                            sameQuesPaperEntity.get(quesIndex).getFavouriteAndNote().getChildList().
                                    get(SubChildAnsweringIndex).getSubChildList().get(0).getSubChildItem().get(0).setStuAnswer("A");
                        }
                    }else if(choiceResult.equals("b")||  choiceResult.equals("boy")){
                        if(OptionSize>=2) {
                            sameQuesPaperEntity.get(quesIndex).getFavouriteAndNote().getChildList().
                                    get(SubChildAnsweringIndex).getSubChildList().get(0).getSubChildItem().get(0).setStuAnswer("B");
                        }
                    }else if(choiceResult.equals("c")){
                        if(OptionSize>=3) {
                            sameQuesPaperEntity.get(quesIndex).getFavouriteAndNote().getChildList().
                                    get(SubChildAnsweringIndex).getSubChildList().get(0).getSubChildItem().get(0).setStuAnswer("C");
                        }
                    }else if( choiceResult.equals("d")||choiceResult.equals("dog")){
                        if(OptionSize>=4) {
                            sameQuesPaperEntity.get(quesIndex).getFavouriteAndNote().getChildList().
                                    get(SubChildAnsweringIndex).getSubChildList().get(0).getSubChildItem().get(0).setStuAnswer("D");
                        }
                    }
                    refreshRecordAnswer();
                }else{
                    if(!mIsExitTranslate) {
                        SkEgnManager.getInstance(getActivity()).startRecord(mCoreType, "", QType.QTYPE_EMPTY, mOnRecordListener);
                        mRecoderUtils.startRecord();
                    }
                }

            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    };

    private void refreshRecordAnswer(){

        int AnsweredCount=0;
        int ChildListSize = sameQuesPaperEntity.get(quesIndex).getFavouriteAndNote().getChildList().size();
        for(int i=0;i<ChildListSize;i++){
            String StuAnswer =  sameQuesPaperEntity.get(quesIndex).getFavouriteAndNote().getChildList().
                    get(i).getSubChildList().get(0).getSubChildItem().get(0).getStuAnswer();
            if(!StuAnswer.equals("")){
                AnsweredCount = AnsweredCount+1;
            }
        }
        //若作答完成则显示答案，记录作答状态，否则亦然
        if (AnsweredCount == ChildListSize) {
            sameQuesPaperEntity.get(quesIndex).getFavouriteAndNote().setSubmitState(2);
            hideRecordMiView();
            SkEgnManager.getInstance(getActivity()).stopRecord();
            mRecoderUtils.stopRecord();
        }else{
            sameQuesPaperEntity.get(quesIndex).getFavouriteAndNote().setSubmitState(1);
            refreshAnswerAdapter();
            SkEgnManager.getInstance(getActivity()).startRecord(mCoreType, "", QType.QTYPE_EMPTY, mOnRecordListener);
            mRecoderUtils.startRecord();
        }
    }

    private String getResult(String result) {

        String choiceSoundResult = "";
        StringBuilder keyValue = new StringBuilder();
        try{
            JSONObject returnObj = new JSONObject(result);
            JSONObject resultJSONObject = returnObj.getJSONObject("result");
            if(resultJSONObject.has("overall")){
                keyValue.append("总    分: " + resultJSONObject.getString("overall") + "\n");
            }
            Log.e("getResultAAAAA", "====返回json========答案=========>" + resultJSONObject.getString("recognition"));
            choiceSoundResult = resultJSONObject.getString("recognition");

        }catch (Exception e){
            e.printStackTrace();
        }
        keyValue.append("\n");
        keyValue.append(JSONTool.stringToJSON(result));

        return choiceSoundResult;
    }


    public interface CallBackFragmentTlxz {
        void submitKgtQuesAnswer();
    }

    private void showRecordVolumeSize(final int volumesize){
        new Thread(new Runnable() {
            @Override
            public void run() {
                Message msg =Message.obtain();
                msg.obj = volumesize;
                msg.what = 1;
                handler.sendMessage(msg);

                try {
                    Thread.sleep(200);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

            }
        }).start();

    }

    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    int VolumeSize = Integer.valueOf(msg.obj.toString());
                    if(VolumeSize>50){
                        VolumeSize=50;
                    }
                    int LevelSize = VolumeSize*200;
                    drawableMi.setLevel(LevelSize);
                    break;
            }
        }
    };

    private void refreshAnswerAdapter(){
        //刷新作答区域
        list.clear();
        int totalItemCountA =  sameQuesPaperEntity.get(quesIndex).getFavouriteAndNote().getChildList().size();
        for(int i=0;i<totalItemCountA;i++) {
            final RecyclerView mRvAnswer = new RecyclerView(getActivity());
            mRvAnswer.setLayoutManager(new LinearLayoutManager(getActivity()));//必须先设置LayoutManager
            SQxlTlxzAnswerAdapter mAnswerAdapter = new SQxlTlxzAnswerAdapter(getActivity(),
                    sameQuesPaperEntity,quesIndex,i,new SQxlTlxzAnswerAdapter.CallBackAdapterTlxz() {
                @Override
                public void callAnsweredAll() {

                }
            });
            mRvAnswer.setAdapter(mAnswerAdapter);
            list.add(mRvAnswer);
        }
        mVpAnswer.setAdapter(new AnswerViewPagerAdapter(list));
        mVpAnswer.setCurrentItem(  sameQuesPaperEntity.get(quesIndex).getFavouriteAndNote().getCurrentSubChildAnswerIndex());
    }


    private boolean mIsExitTranslate = false;
    @Override
    public void onDestroyView() {
        super.onDestroyView();
        Log.e("onDestroy","=====fragment=======退出错难题训练========11111======"+quesIndex);
        if(mRecoderUtils!=null) {
            SkEgnManager.getInstance(getActivity()).stopRecord();
            mRecoderUtils.stopRecord();
            mIsExitTranslate = true;
        }

    }

}